package main

import (
	_ "github.com/go-sql-driver/mysql"
	"database/sql"
	"fmt"

)

func main(){
	db, err := sql.Open("mysql", "root:zqd6382639@/test?charset=utf8")
	checkErr(err)
	defer db.Close()

	//stmt, _ := db.Prepare(`INSERT user (user_name,user_age,user_sex) values (?,?,?)`)
	//res, _ := stmt.Exec("tony", 20, 1)
	//id, _ := res.LastInsertId()
	//
	//fmt.Println(id)
	//插入数据
	//stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
	stmt, err := db.Prepare("INSERT userinfo (username,departname,created) VALUE (?,?,?)")
	checkErr(err)

	res, _ := stmt.Exec("hanzi baidu", 25, 1)


	id, err := res.LastInsertId()
	checkErr(err)

	fmt.Println(id)

		//更新数据
		stmt, err = db.Prepare("update userinfo set username=? where uid=?")
		checkErr(err)

		res, err = stmt.Exec("astaxieupdate", id)
		checkErr(err)

		affect, err := res.RowsAffected()
		checkErr(err)

		fmt.Println("affect=",affect)

		//查询数据
		rows, err := db.Query("SELECT * FROM userinfo")
		checkErr(err)

		for rows.Next() {
			var uid int
			var username string
			var department string
			var created string
			err = rows.Scan(&uid, &username, &department, &created)
			checkErr(err)
			fmt.Println(uid)
			fmt.Println(username)
			fmt.Println(department)
			fmt.Println(created)
		}
/*
		//删除数据
		stmt, err = db.Prepare("delete from userinfo where uid=?")
		checkErr(err)

		res, err = stmt.Exec(id)
		checkErr(err)

		affect, err = res.RowsAffected()
		checkErr(err)

		fmt.Println(affect)
*/
	//db.Close()
}


func checkErr(err error) {
	if err != nil {
		fmt.Println(err)
	}
}